//
//  NoctionTableView.m
//  dyseller
//
//  Created by 红喇叭 on 2017/8/17.
//  Copyright © 2017年 红喇叭. All rights reserved.
//

#import "NoctionTableView.h"
#import "PayOrderViewController.h"
#import "myWkWebViewController.h"
#import "OrderListModel.h"

@implementation NoctionTableView

- (instancetype)initWithFrame:(CGRect)frame tableData:(NSArray *)arrData stlye:(int)style{
    self = [super initWithFrame:frame];
    if(self){
        _data = arrData.mutableCopy;
        _style = style;
        self.backgroundColor = [UIColor whiteColor];
        self.tableView.backgroundColor = [UIColor whiteColor];
        self.tableView.scrollEnabled = NO;
        if(_data.count > 2){
            self.tableView.scrollEnabled = YES;
            for(int i=0;i<2;i++){
                [_data addObject:arrData[i]];
            }
            [self setupTimer];
        }
    }
    return self;
}


- (void)layoutSubviews{
    [self.tableView reloadData];
}
- (void)rloadView:(NSArray *)arrdata style:(int)style{
    _data = arrdata.mutableCopy;
    _style = style;
    if(_data.count > 2){
        self.tableView.scrollEnabled = YES;
        for(int i=0;i<2;i++){
            [_data addObject:arrdata[i]];
        }
    }
    [self.tableView reloadData];
}

- (UITableView *)tableView{
    if(_tableView == nil){
        _tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_W, self.height) style:UITableViewStylePlain];
        _tableView.delegate = self;
        _tableView.dataSource = self;
        [_tableView registerNib:[UINib nibWithNibName:@"OrderNoticeCell" bundle:nil] forCellReuseIdentifier:@"OrderNoticeCell"];
        //UITableView去掉自带系统的分割线
        _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        [self addSubview:_tableView];
    }
    
    return _tableView;
}




- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return _data.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    NSDictionary *dic = _data[indexPath.row];
    UITableViewCell *cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"Cell"];
    UILabel *titleLba = [[UILabel alloc] initWithFrame:CGRectMake(0, GETHEIGHT(16), self.width, GETHEIGHT(40))];
    if(_data.count==1){
        titleLba.centerY = self.height/2;
    }else{
        titleLba.centerY = self.height/4;
    }
    [cell.contentView addSubview:titleLba];
    if(_style == 0){
        titleLba.text = [NSString stringWithFormat:@"系统消息：%@",dic[@"title"]];
    
    }else{
        OrderListModel *orderModel = [OrderListModel yy_modelWithJSON:dic];
        NSString *textStr = orderModel.order_sn;
        textStr = [textStr substringFromIndex:7];
        textStr = [NSString stringWithFormat:@"***%@",textStr];
        titleLba.text = [NSString stringWithFormat:@"%@：%@",orderModel.type,textStr];
        
        titleLba.width = [ToolClass heighW:font14 titleStr:titleLba.text].width;
        
        UILabel *price = [[UILabel alloc] initWithFrame:CGRectMake(titleLba.right, GETHEIGHT(16), self.width-titleLba.right, GETHEIGHT(40))];
        price.centerY = titleLba.centerY;
        price.text = [NSString stringWithFormat:@"￥%@",orderModel.price];
        price.textAlignment = NSTextAlignmentRight;
        price.font = font14;
        price.textColor = [UIColor redColor];
        
        if([orderModel.price isEqualToString:@"0.00"]){
            price.text = [NSString stringWithFormat:@"%@紫喇叭",orderModel.point_pay];
            price.textColor = UIColorFromRGB(0xfd5974);
        }else{
            if(orderModel.point_pay&&([orderModel.point_pay intValue]>0)){
                NSString *str = [NSString stringWithFormat:@"￥%@+%@",orderModel.price,orderModel.point_pay];
                NSString *integral = dic[@"point_pay"];
                price.attributedText = [ToolClass AttributedString:str range:NSMakeRange(str.length-integral.length,integral.length) color:UIColorFromRGB(0xfd5974)];
            }else{
                price.text = [NSString stringWithFormat:@"￥%@",orderModel.price];
            }
        }
        [cell.contentView addSubview:price];
    }
    titleLba.font = font14;
    titleLba.textColor = [UIColor orangeColor];
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    
    return cell;
    
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    if(_style == 0){
        NSString *noticID = _data[indexPath.row][@"id"];
        myWkWebViewController *vc = [[myWkWebViewController alloc] init];
        NSString *url = [NSString stringWithFormat:@"%@/ShopApi/Html/itemDetail?noticeId=%@&flag=1",APP_HOST_ADDRESS,noticID];
        vc.myurl = url;
        vc.toTitle = @"公告详情";
       [[ToolClass viewController:self].navigationController pushViewController:vc animated:YES];
    }else{
        NSString *orderID = _data[indexPath.row][@"order_sn"];
        __weak typeof(self)weakself = self;
            PayOrderViewController *vc = [[PayOrderViewController alloc] initWith:@[] style:1];
            vc.orderStr = orderID;
            vc.fromVC = 2;
            [[ToolClass viewController:weakself].navigationController pushViewController:vc animated:YES];
        
    }
    
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    if(_data.count == 1){
        return self.height;
    }
    return self.height/2.0;
}

- (void)setupTimer {
    if (_data.count > 1 ) {
        //设置好滚动视图，启动定时器
        if (!self.timer && _data.count>2) {
            self.timer = [self createTimer];
            [[NSRunLoop mainRunLoop] addTimer:self.timer forMode:NSRunLoopCommonModes];
        }
    }
}

- (NSTimer*)createTimer {
    NSTimer *timer = [NSTimer scheduledTimerWithTimeInterval:2 target:self selector:@selector(autoScrollAd) userInfo:nil repeats:YES];
    [[NSRunLoop currentRunLoop] addTimer:timer forMode:NSRunLoopCommonModes];
    return timer;
}

- (void)autoScrollAd {
    
    NSInteger y = self.tableView.contentOffset.y/(self.height/2);
    //显示最后一张，移动offset到最左边
    if (y == _data.count - 2) {
        self.tableView.contentOffset = CGPointZero;
        y = 0;
        
    }
    //滚动到下一页
    [UIView animateWithDuration:0.5 animations:^{
        
        self.tableView.contentOffset = CGPointMake(0,(y+1)*(self.height/2));
    } completion:^(BOOL finished) {
        //衔接自动滚动后手动滑动
        self.lastX = self.tableView.contentOffset.y;
        
    }];
    
    
    
    
}


#pragma mark scrollView代理方法
- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView {
    
    NSInteger offY = scrollView.contentOffset.y/(self.height/2);
    
    if (offY == 0 && _data.count>2) {
        //滑动到第一张
        scrollView.contentOffset = CGPointMake(0,(_data.count-2)*(self.height/2));
        
    } else if (offY == _data.count-2) {
        //滑动到最后一张
        self.tableView.contentOffset = CGPointZero;
    }
    
    self.lastX = scrollView.contentOffset.y;
    
    if (self.manual && _data.count>2) {
        self.timer = [self createTimer];
        self.manual = NO;
    }
    
}

- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView {
    //如果手动滑动，先取消定时器
    self.manual = YES;
    if (self.timer != nil) {
        [self.timer invalidate];
    }
}

- (void)scrollViewDidScroll:(UIScrollView *)scrollView {
    
    
}

//scrollview的滑动不是“自然停止”的而是“手动停止”所以scrollViewDidEndDecelerating函数就不会被执行。所以需要在下面这个方法处理，将scrollViewDidEndDecelerating里面的代码在此方法再次执行
-(void) scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate{
    
    if (decelerate){
        //这里写上停止时要执行的代码
        NSInteger offy = scrollView.contentOffset.y/(self.height/2);
        
        if (offy == 0) {
            //滑动到第一张
            scrollView.contentOffset = CGPointMake(0,(_data.count-1)*(self.height/2)+20);
            
        } else if (offy == _data.count-1) {
            //滑动到最后一张
            self.tableView.contentOffset = CGPointZero;
        }
        
        self.lastX = scrollView.contentOffset.y;
        
        if (self.manual && _data.count>2) {
            self.timer = [self createTimer];
            self.manual = NO;
        }
        
    }
    
}

- (void)stopTimer{
    [self.timer invalidate];
    self.timer = nil;
}

@end
